package servlet;

import bean.User;
import service.Query;
import service.impl.QueryImpl;
import utills.JsonUtils;
import utills.ListObject;
import utills.ResponseUtils;
import utills.StatusCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author Keven-赵仕星
 * @date 2022/6/6 17:51
 */
@WebServlet("/QueryAllServlet")
public class QueryAllServlet extends HttpServlet {

    public void init(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Query query = new QueryImpl();
        try {
            List<User> users = query.queryAll();
            /**
             * 封装json
             * **/
            ListObject listObject=new ListObject();
            listObject.setLength(users.size());
            listObject.setItems(users);
            listObject.setCode(StatusCode.CODE_SUCCESS);
            listObject.setMsg("成功");
            ResponseUtils.renderJson(resp, JsonUtils.toJson(listObject));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

}
